package com.tanhua.sso.server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.api.UserInfoService;
import com.tanhua.api.VoiceServiceApi;
import com.tanhua.config.UserHolder;
import com.tanhua.exceptionhander.CustomException;
import com.tanhua.sso.dto.Voice;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.VoiceVo;
import com.tanhua.util.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;

@Service
public class PeachblossomService {

    @Autowired
    protected FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @DubboReference
    private VoiceServiceApi voiceServiceApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserInfoService userInfoService;

    //挑花传音
    public void sendPeachblossom(MultipartFile soundFile) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        String uri= null;
        try {
            //获取文件格式
            int lastIndexOf = soundFile.getOriginalFilename().lastIndexOf(".");
            String format = soundFile.getOriginalFilename().substring(lastIndexOf + 1);
            //上传,返回文件路径
            StorePath storePath = fastFileStorageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), format, null);
            //拼接文件路径
            uri = fdfsWebServer.getWebServerUrl()+"/"+storePath.getFullPath();
        } catch (IOException e) {
            throw new CustomException("语音上传失败");
        }
        Voice voice=new Voice();
        voice.setCreated(System.currentTimeMillis());
        voice.setUserId(userId);
        voice.setSeeType(0);
        voice.setVideoUrl(uri);
        //添加语音
        voiceServiceApi.insert(voice);
    }

    //接收语音
    public VoiceVo acceptPeachblossom() {
        Voice voice =new Voice();
        VoiceVo voiceVo=new VoiceVo();
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //获取当前用户的信息
        UserInfo userInfo = userInfoService.selectUser(userId);

        UserInfo user=new UserInfo();
        //获取缓存中是否有数据
        String key= Constants.VOICE+userId;
        String value = redisTemplate.opsForValue().get(key);
        //查看次数
        Integer count = Convert.toInt(value);
        if (ObjectUtil.isNotEmpty(count)){
            if (count>10){
                throw new CustomException("次数已用尽");
            }else {
                //查看语音
                voice=voiceServiceApi.selectOne();
                Long voiceUserId = voice.getUserId();
                user = userInfoService.selectUser(voiceUserId);
                if (user.getGender().equals(userInfo.getGender())){
                String newCount = Convert.toStr(count + 1);
                //新增一次
                redisTemplate.opsForValue().getAndSet(key,newCount);
                }
            }
        }else {
            //当前日期加一天
            LocalDate now = LocalDateTime.now().toLocalDate().plusDays(1);
            //失效时间点
            long endTime = Date.from(now.atStartOfDay(ZoneOffset.ofHours(8)).toInstant()).getTime();
            //当前时间的毫秒值
            long startTime = new Date().getTime();
            //设置过期时间一天
            redisTemplate.opsForValue().set(key,"0",Duration.ofMillis( endTime-startTime));
            //查看语音
            voice=voiceServiceApi.selectOne();
            Long voiceUserId = voice.getUserId();
            user = userInfoService.selectUser(voiceUserId);
            if (user.getGender().equals(userInfo.getGender())){
                String newCount = Convert.toStr(count + 1);
                //新增一次
                redisTemplate.opsForValue().getAndSet(key,newCount);
            }
        }
        //获取已查看次数
        String nowCount = redisTemplate.opsForValue().get(key);
        //获取还剩的次数\
        Integer remainingTimes=10-Convert.toInt(nowCount);
        BeanUtils.copyProperties(user,voiceVo);
        voiceVo.setSoundUrl(voice.getVideoUrl());
        voiceVo.setRemainingTimes(remainingTimes);


        return voiceVo;
    }
}
